//
//  YYQiniu.swift
//  YYProject
//
//  Created by 陆文宇 on 2017/9/4.
//  Copyright © 2017年 陆文宇. All rights reserved.
//

import Qiniu

final class YYQiniu {
    
    static func upload(_ data: Data, key: String, token: String, success: @escaping (String) -> Void, failure: @escaping () -> Void) {
        
        let isHttps = true
        let httpsZone = QNAutoZone(https: isHttps)
        let config = QNConfiguration.build { (builder) in
            builder?.setZone(httpsZone)
        }
        
        let upManager = QNUploadManager(configuration: config)
        upManager?.put(data, key: key, token: token, complete: { (info, key, resp) in
            if let info = info,
                let key = key,
                let resp = resp {
                
                if info.isOK {
                    success(key)
                } else {
                    failure()
                }
                
                yy_Log("info: \(info)")
                yy_Log("resp: \(resp)")
            } else {
                failure()
            }
        }, option: nil)
    }
    
    static func multipleUpload(data: [String: Data], token: String, success: @escaping ([String]) -> Void, failure: @escaping () -> Void) {
        let isHttps = true
        let httpsZone = QNAutoZone(https: isHttps)
        let config = QNConfiguration.build { (builder) in
            builder?.setZone(httpsZone)
        }
        
        let upManager = QNUploadManager(configuration: config)
        
        var filenames = [String]()
        data.forEach { (dt) in
            upManager?.put(dt.value, key: dt.key, token: token, complete: { (info, key, resp) in
                if let info = info,
                    let key = key,
                    let resp = resp {
                    
                    if info.isOK {
                        filenames.append(key)
                        if filenames.count == data.count {
                            success(filenames)
                        }
                    } else {
                        failure()
                    }
                    
                    yy_Log("info: \(info)")
                    yy_Log("resp: \(resp)")
                } else {
                    failure()
                }
            }, option: nil)
        }
    }
    
}
